'use strict';

const Controller = require('egg').Controller;

class PeopleController extends Controller {
  async index() {
    this.ctx.body = 'hi, egg';
  }
  async getPeople() {
    var count = await this.ctx.app.db.all('select count (*) as count from people')
    let sql = `SELECT p.*,s.name as schoolName 
    FROM people as p inner join school as s 
on p.number=s.number where 1=1 `
    let query = this.ctx.query
    let index = query.pageSize * (query.pageIndex - 1)
    if (query.searchKey) {
      sql += ` and p.name like '%${query.searchKey}%'`
      count = await this.ctx.app.db.all(`select count (*) as count from people where name like '%${query.searchKey}%'`)
    }
    if (query.pageSize && query.pageIndex) {
      sql += ` order by id  desc limit ${query.pageSize} offset ${index} `
    }
    var result = await this.ctx.app.db.all(sql)

    let res = {
      data: result,
      count
    }
    this.ctx.body = res
  }
  async setPeople() {
    const { db } = this.ctx.app;
    let peoples = this.ctx.request.body
    let people = {}
    for (var key in peoples) {
      people['$' + key] = peoples[key]
    }
    let sql = `select * from people  where id='${people.$id}'`
    var result = await db.all(sql)
    var res;
    console.log(people.$type)
    if (result.length) {
      var a = { $type: people.$type, $id: people.$id }
      res = await db.run(`update people set type=$type where id=$id`, a);
    } else {
      res = await db.run(`insert into people (id,vid,number,name,headImage,type,nation,startDate,endDate,issue,address,sex,shootphoto,birthday)
      values ($id,$vid,$number,$name,$headImage,$type,$nation,$startDate,$endDate,$issue,$address,$sex,$shootphoto,$birthday)`, people);
    }
    // let peoples = this.ctx.request.body.peoples
    // let people = peoples.map((i) => {
    //   for (var key in i) {
    //     i['$' + key] = i[key]
    //     delete i[key]
    //   }
    //   return i;
    // });
    // console.log(people, '数组对象')
    // let res;
    // for (var i = 0; i < people.length; i++) {
    //   res += await db.run(`insert into people (id,vid,number,name,headImage,type,nation,startDate,endDate,issue,address,sex,shootphoto,birthday)
    //   values ($id,$vid,$number,$name,$headImage,$type,$nation,$startDate,$endDate,$issue,$address,$sex,$shootphoto,$birthday)`, people[i]);
    // }
    this.ctx.body = res
  }
  async delPeople() {
    const { db } = this.ctx.app;
    const id = this.ctx.request.query.id
    const res = await db.run(`delete from people where id = ${id}`);
    this.ctx.body = res
  }
  async byNumber() {
    const action = this.ctx.params.action
    const { db } = this.ctx.app;
    const id = this.ctx.request.query.number
    let sql;
    if (id) {
      sql = `select * from  people  where number = ${id} and (type in(1,2)) `
    } else {
      sql = `select * from  people  type in(1,2)`
    }
    var result = await db.all(sql)
    this.ctx.body = result
  }
}

module.exports = PeopleController;
